import { Injectable, OnModuleInit, Logger, Global } from '@nestjs/common';
import { PrismaClient } from 'generated/prisma';


@Global()
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  private readonly logger = new Logger(PrismaService.name);

  constructor() {
    super({
      log: [
        { emit: 'event', level: 'query' },
        { emit: 'stdout', level: 'info' },
        { emit: 'stdout', level: 'warn' },
        { emit: 'stdout', level: 'error' },
      ],
    });
    // @ts-ignore
    this.$on('query', (e:any) => {
      this.logger.log(`查询: ${e.query}`);
      this.logger.log(`参数: ${e.params}`);
      this.logger.log(`持续时间: ${e.duration}ms`);
    });
  }

  async onModuleInit() {
    await this.$connect().then(res=>{
      this.logger.log('数据库连接成功')
    }).catch(err=>{
      this.logger.error('数据库连接失败', err)
    })
  }

  
}
